package com.cf.util;

import com.cf.constant.EnumReturnCode;
import com.cf.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.web.context.WebApplicationContext;

import java.lang.annotation.Annotation;
import java.util.Map;


/**
 * game-server-SpringBeanUtil
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/5/16 下午 01:16
 */
@Slf4j
public class SpringBeanUtil {

    public SpringBeanUtil(ApplicationContext applicationContext) {
        log.info("实例化SpringBeanUtil，设置applicationContext");
        this.applicationContext = applicationContext;
    }

    private static ApplicationContext applicationContext;

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }


    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    //通过class获取Bean.
    public static Map<String, Object> getBeanWithAnnotation(Class<? extends Annotation> clazz) {
        return getApplicationContext().getBeansWithAnnotation(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    public static WebApplicationContext getWebApplicationContext() throws BizException {
        if (applicationContext != null && applicationContext instanceof WebApplicationContext)
            return (WebApplicationContext) applicationContext;
        else
            throw new BizException(EnumReturnCode.ERROR.getCode(), "当前非web环境");
    }
}


